package pl.edu.agh.sius.gui;

import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

import pl.edu.agh.sius.ldap.Ldap;
import pl.edu.agh.sius.ldap.User;

public class SignUpJPanel extends JPanel{
	private static final long serialVersionUID = -89936201121864601L;
	
	private Ldap ldap;
	
	public void init(){
		setLayout(new GridBagLayout());
		setPreferredSize(new Dimension(80, 100));
		
		final JLabel signUpFailedLabel = new JLabel("Typed username already exists.");
		
		JLabel signUpLabel = new JLabel("Login:");
		final JTextField signUpTextField = new JTextField(40);
		signUpLabel.setLabelFor(signUpTextField);
		
		JLabel passwordLabel = new JLabel("Password:");
		final JTextField passwordTextField = new JTextField(40);
		passwordLabel.setLabelFor(passwordTextField);
		
		JButton signUpButton = new JButton("Sign Up");
		
		signUpButton.addActionListener(new ActionListener() {
        	public void actionPerformed(ActionEvent e) {
        		User user = new User(signUpTextField.getText(),passwordTextField.getText(),MainJTabbedPane.localServerAddress);
        		if(ldap.createUser(user)) {
        			ldap.authenticate(user);
            		ldap.resetUserAddress(user.getUsername(),MainJTabbedPane.localServerAddress);
        			((MainJTabbedPane)getParent()).userLoggedIn(user.getUsername());
        			getParent().getParent().setName("P2P Client. Logged as " + user);
        		} else {
        	    	signUpFailedLabel.setVisible(true);
        		}
        	}
        });
		
		GridBagConstraints c = new GridBagConstraints();
    	c.fill = GridBagConstraints.HORIZONTAL;
    	c.insets = new Insets(0, 10, 0, 10);
    	c.anchor = GridBagConstraints.NORTH;
    	c.weightx = 0.5;
    	c.weighty = 0.5;
    	
    	c.gridy = 0;
    	c.gridx = 0;
		this.add(signUpLabel,c);
		
    	c.gridx = 1;
		this.add(signUpTextField,c);
		
    	c.gridy = 1;
    	c.gridx = 0;
		this.add(passwordLabel,c);
		
    	c.gridx = 1;
		this.add(passwordTextField,c);

    	c.gridy = 2;
    	c.gridx = 0;
    	this.add(signUpButton,c);
    	
    	c.gridy = 3;
    	this.add(signUpFailedLabel,c);
    	signUpFailedLabel.setVisible(false);
	}

	public Ldap getLdap() {
		return ldap;
	}

	public void setLdap(Ldap ldap) {
		this.ldap = ldap;
	}

	
}
